class Event {
  constructor() {
    // 存储事件
    this.callbacks = {};
  }

  // 监听
  $on(name, fn) {
    // 一个名字可以订阅多个事件函数
    (this.callbacks[name] || (this.callbacks[name] = [])).push(fn);
  }

  // 触发
  $emit(name, arg, context) {
    let cbs = this.callbacks[name];
    if (cbs) {
      cbs.forEach((v) => {
        v.call(context, arg);
      });
    }
  }

  // 移除事件
  $off(name) {
    this.callbacks[name] = null;
  }

  // 触发一次
  $once(name, fn) {
    const wrapFn = ()=>{
        fn();
        this.$off(name, wrapFn);
    }
    this.$on(name, fn);
  }
}

// 简单使用
let event = new Event();
event.$on("event1", function (arg) {
  console.log("事件1", arg);
});

event.$on("event2", function (arg) {
  console.log("事件2", arg);
});

event.$emit("event1", { name: "anyway" });
event.$emit("event2", { age: "20" });